package com.caimiao.miao.library.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Build;

import java.io.IOException;

/**
 * MediaPlayer：资源占用量较高、延迟时间较长、不支持多个音频同时播放等
 */
public class VoiceMediaPlayer implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {
    private static VoiceMediaPlayer instance;

    private MediaPlayer mPlayer;

    public static VoiceMediaPlayer getInstance() {
        if (instance == null)
            instance = new VoiceMediaPlayer();
        return instance;
    }

    private VoiceMediaPlayer() {
        mPlayer = new MediaPlayer();
        mPlayer.setOnPreparedListener(this::onPrepared);
        mPlayer.setOnCompletionListener(this::onCompletion);
    }


    public void playFromAsset(Context context, String fileName, int priority) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                stop();
                mPlayer.setDataSource(context.getAssets().openFd(fileName));
                mPlayer.prepareAsync();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void playFromRes(Context context, int resId) {
        AssetFileDescriptor afd = context.getResources().openRawResourceFd(resId);
        if (afd == null) return;
        try {
            stop();
            mPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void playFromFileOrUrl(String path) {
        try {
            stop();
            mPlayer.setDataSource(path);
            mPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stop() {
        if (mPlayer != null && mPlayer.isPlaying())
            mPlayer.stop();
        mPlayer.reset();
    }

    public void release() {
        mPlayer.release();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        mPlayer.stop();
        mPlayer.release();
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mPlayer.start();
    }
}
